<?php
/**
 * @author	barbarosalcin
 * @desc	functions class, implementing methods which may be used by core
 * @package	core
 * @version	$Id: 20110216
 * @desc	I hate 8859..
 *
 */
/**
 * Changelog
 * @since 20101201 + function create_guid()
 * @since 20110216 + function validate_email()
 */

class functions
{
	
	public $charset = 'UTF-8';
	public $extraChars = 'üöçşğıÜÖÇŞĞİ';
	
	function generatePassword($length = 8)
	{
		
		// start with a blank password
		$password = "";
		
		// define possible characters
		$possible = "23456789abcdefghjkmnprstuwvyz";
		
		// set up a counter
		$i = 0;
		
		// add random characters to $password until $length is reached
		while($i < $length)
		{
			
			// pick a random character from the possible ones
			$char = substr($possible, mt_rand(0, strlen($possible) - 1), 1);
			
			// we don't want this character if it's already in the password
			if (! strstr($password, $char))
			{
				$password .= $char;
				$i++;
			}
		
		}
		
		// done!
		return $password;
	
	}
	
	function trim($input)
	{
		if (is_string($input))
			$input = trim($input);
		elseif (is_array($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_array($val))
					$input[$key] = trim($val);
				else
					$input[$key] = $this->trim($val);
			}
		}
		elseif (is_object($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_object($val))
					$input->$key = trim($val);
				else
					$input->$key = $this->trim($val);
			}
		}
		return $input;
	}
	
	function addSlash($input)
	{
		if (is_string($input))
			$input = addslashes(trim($input));
		elseif (is_array($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_array($val))
					$input[$key] = addslashes(trim($val));
				else
					$input = $this->addSlash($input);
			}
		}
		elseif (is_object($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_object($val))
					$input->$key = addslashes(trim($val));
				else
					$input = $this->addSlash($input);
			}
		}
		return $input;
	}
	
	function delSlash($input)
	{
		if (is_string($input))
			$input = stripslashes(trim($input));
		elseif (is_array($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_array($val))
					$input[$key] = stripslashes(trim($val));
				else
					$input = $this->delSlash($input);
			}
		}
		elseif (is_object($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_object($val))
					$input->$key = stripslashes(trim($val));
				else
					$input = $this->delSlash($input);
			}
		}
		return $input;
	}
	
	function html($input)
	{
		if (is_string($input))
			$input = htmlspecialchars(trim($input));
		elseif (is_array($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_array($val))
					$input[$key] = htmlspecialchars(trim($val));
				else
					$input = $this->html($input);
			}
		}
		elseif (is_object($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_object($val))
					$input->$key = htmlspecialchars(trim($val));
				else
					$input = $this->html($input);
			}
		}
		return $input;
	}
	
	function lower($input)
	{
		if (is_string($input))
		{
			$input = str_replace('İ', 'i', $input);
			$input = str_replace('I', 'ı', $input);
			$input = mb_strtolower(trim($input), 'UTF-8');
		}
		elseif (is_array($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_array($val))
				{
					$val = str_replace('İ', 'i', $val);
					$val = str_replace('I', 'ı', $val);
					$input[$key] = mb_strtolower(trim($val), 'UTF-8');
				}
				else
					$input = $this->lower($input);
			}
		}
		elseif (is_object($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_object($val))
				{
					$val = str_replace('İ', 'i', $val);
					$val = str_replace('I', 'ı', $val);
					$input->$key = mb_strtolower(trim($val), 'UTF-8');
				}
				else
					$input = $this->lower($input);
			}
		}
		return $input;
	}
	
	function upper($input)
	{
		if (is_string($input))
		{
			$input = str_replace('i', 'İ', $input);
			$input = str_replace('ı', 'I', $input);
			$input = mb_strtoupper(trim($input), 'UTF-8');
		}
		elseif (is_array($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_array($val))
				{
					$val = str_replace('i', 'İ', $val);
					$val = str_replace('ı', 'I', $val);
					$input[$key] = mb_strtoupper(trim($val), 'UTF-8');
				}
				else
					$input = $this->upper($input);
			}
		}
		elseif (is_object($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_object($val))
				{
					$val = str_replace('i', 'İ', $val);
					$val = str_replace('ı', 'I', $val);
					$input->$key = mb_strtoupper(trim($val), 'UTF-8');
				}
				else
					$input = $this->upper($input);
			}
		}
		return $input;
	}
	
	function replace($find, $replace, $input)
	{
		if (is_string($input))
			$input = str_replace($find, $replace, trim($input));
		elseif (is_array($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_array($val))
					$input[$key] = str_replace($find, $replace, trim($val));
				else
					$input = $this->replace($input);
			}
		}
		elseif (is_object($input))
		{
			foreach ( $input as $key => $val )
			{
				if (! is_object($val))
					$input->$key = str_replace($find, $replace, trim($val));
				else
					$input = $this->replace($input);
			}
		}
		return $input;
	}
	
	function makeSeo($text)
	{
		$text = str_replace(' ', '-', trim($text));
		$tr_array = array(
				'Ğ', 
				'Ü', 
				'Ş', 
				'İ', 
				'Ö', 
				'Ç', 
				'ğ', 
				'ü', 
				'ş', 
				'ı', 
				'ö', 
				'ç');
		$en_array = array(
				'g', 
				'u', 
				's', 
				'i', 
				'o', 
				'c', 
				'g', 
				'u', 
				's', 
				'i', 
				'o', 
				'c');
		$text = str_replace($tr_array, $en_array, $text);
		$text = preg_replace('/[^A-Za-z0-9+-]+/i', '', $text);
		
		$text = preg_replace('/İ/', 'i', $text);
		$text = preg_replace('/[-]+/', '-', $text);
		$text = $this->lower($text);
		$text = trim($text, '-');
		return $text;
	}
	
	function __destruct()
	{
		$this->charset = '';
	}
	
	function recScriptAdd($r_array, $dirname, $filetype, $dirIncluded = false, $keyStrip = '')
	{
		if ($handle = opendir($dirname))
		{
			
			while(false !== ($file = readdir($handle)))
			{
				
				if ((is_file($dirname . '/' . $file)) && (substr($file, strrpos($file, '.')) == $filetype))
				{
					if ($dirIncluded)
					{
						$key = substr(str_replace($keyStrip, '', $file), 0, - 4);
						$r_array[$key] = $dirname . '/' . $file;
					}
					else
					{
						$key = substr(str_replace($keyStrip, '', $file), 0, - 4);
						$r_array[$key] = $file;
					}
				
				}
				else
				{
					if (($file != '..') && ($file != '.') && (substr($file, strrpos($file, '.')) == '.svn'))
					{
						$this->recScriptAdd($r_array, $dirname, $filetype, $dirIncluded, $keyStrip);
					}
				}
			}
			closedir($handle);
		}
		return $r_array;
	}
	
	function encode_ip($dotquad_ip)
	{
		$ip_sep = explode('.', $dotquad_ip);
		return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
	}
	
	function decode_ip($int_ip)
	{
		$hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
		return hexdec($hexipbang[0]) . '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
	}
	
	function date2int($date, $delimiter = '/')
	{
		$tmp = explode($delimiter, $date);
		return mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
	}
	
	/**
	 * @author barbrosalcin
	 * @desc google sitemap updater
	 * @param string $siteurl - trailing slash required !important
	 * @param string $xmlfile
	 * @return 0/1
	 */
	function ping_google($siteurl, $xmlfile)
	{
		$ch = curl_init();
		
		curl_setopt($ch, CURLOPT_URL, "http://www.google.com/webmasters/tools/ping?sitemap=" . urlencode($siteurl . $xmlfile));
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_NOBODY, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$status = (curl_exec($ch) === false) ? 0 : 1;
		
		// Close handle
		curl_close($ch);
		return $status;
	}
	
	/**
	 * @author barbrosalcin
	 * @desc google sitemap.xml parser
	 * @param string $xmlfile
	 * @return 0/1
	 */
	function add2sitemap($siteurl, $xmlfile, $pageurl, $prio = '0.7', $freq = 'weekly')
	{
		$fp = simplexml_load_file($xmlfile);
		$sm = $fp->addChild('url');
		$sm->addChild('loc', $siteurl . $pageurl);
		$sm->addChild('priority', $prio);
		$sm->addChild('lastmod', date("Y-m-d"));
		$sm->addChild('changefreq', $freq);
		$xml = $fp->asXML();
		file_put_contents($xmlfile, $xml);
		unset($xml);
		//return $this->ping_google($siteurl,$xmlfile);
		return true;
	}
	
	function create_guid()
	{
		if (function_exists('com_create_guid'))
		{
			return preg_replace('%[{}]%i', '', com_create_guid());
		}
		else
		{
			mt_srand((double) microtime() * 10000);
			$charid = strtoupper(md5(uniqid(rand(), true)));
			$hyphen = chr(45); // "-"
			$uuid = chr(123) . substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12) . chr(125); // "}"
			return preg_replace('%[{}]%i', '', $uuid);
		}
	}
	
	function validate_guid($guid)
	{
		return preg_match('!^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$!i', $guid);
	}
	
	function validate_email($email)
	{
		return preg_match('/[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i', $email);
	
	}
	
	function generate_thumb($eh, $filename, $thumbnail, $params)
	{
		if($filename == '' || empty($params) || $thumbnail == '') {
			return true;
		}
		include_once (__PHPROOT__ . "classes" . DS . "phpthumb" . DS . "phpthumb.class.php");
		$phpThumb = new phpThumb();

		$phpThumb->resetObject();
		$phpThumb->setSourceFilename('../../../' . $filename);
		
		parse_str($params, $params);
		
		foreach ( $params as $k => $v )
		{
			$phpThumb->setParameter($k, $v);
		}
		
		
		
		if (! is_dir(dirname($thumbnail)))
		{
			mkdir(dirname($thumbnail), 0777, true);
		}
		
		$phpThumb->setParameter('config_output_format', 'png');
		
		if (! $phpThumb->GenerateThumbnail())
		{
			$eh->message_die('thumbnail', implode("\n\n", $phpThumb->debugmessages), __LINE__, __FILE__);
		}
		else
		{
			if (! $phpThumb->RenderToFile('../../../' . $thumbnail))
			{
				$eh->message_die('thumbnail', implode("\n\n", $phpThumb->debugmessages), __LINE__, __FILE__);
			}
		}
	}
	
	function move_file($eh, $source, $destination)
	{
		if ($source == $destination || $source == '' || $destination == '')
		{
			return true;
		}
		
		if (! is_dir(dirname($destination)))
		{
			// @todo error
			if (! mkdir(dirname($destination), 0777, true))
			{
				$eh->message_die('move_file', 'mkdir', __LINE__, __FILE__);
				return false;
			}
		}
		
		if (! copy($source, $destination))
		{
			$eh->message_die('move_file', 'copy', __LINE__, __FILE__);
			return false;
		
		}
		unlink($source);
	}
	
	function process_labels($output,$array){

		foreach($array as $k=>$v){
			$tmp["[".$k."]"] = $v; 
		}

		return str_replace(array_keys($tmp),$tmp,$output);
	}
	/**
	 * @desc Maybe later.
	 * Enter description here ...
	 * @param unknown_type $type
	 * @param unknown_type $required
	 * @param unknown_type $columns
	 * @param unknown_type $classes
	 * @param unknown_type $data
	 * @param unknown_type $special
	 * @param unknown_type $values
	 * @param unknown_type $collapsed
	 */
	function generate_field($type='text',$required='0',$columns='2',$classes='',$data=array(),$special='',$values = array(),$collapsed=''){

	    
	    if($required == 1)
	    {
	     $classes .= ' required';   
	    }
	    
	    $item = array(
	    'type' => (string) $type,
	    'required' => !intval($required) ? '0' : '1',
	    'columns' => !intval($columns) ? '2' : $columns,
	    'classes' => $classes,
	    'special' => $special,
	    'collapsed' => (int) $collapsed,
	    'data' => $data,
	    'values' => $values
	    
	    );
	    
	    
	    return $item;
	}

}